<template>
  <el-dialog v-model="fileDialog" title="重命名">
    <el-input
      v-model="curFileNameNodo"
      placeholder="请输入文件名"
      clearable
    ></el-input>
    <el-button
      class="dialogButton"
      type="primary"
      @click="resetFilename(value)"
    >
      确定
    </el-button>
  </el-dialog>
  <el-dialog v-model="newDialog" title="新建文件夹">
    <el-input v-model="name" placeholder="文件夹名称" clearable />
    <el-button class="dialogButton" type="primary" @click="newFileSubmit">
      提交
    </el-button>
  </el-dialog>

  <el-dialog v-model="upFilesDialog" title="上传">
    <!-- todo 
    做一个集合for 用来存储多个文件的绝对路径
     -->

    <el-input v-model="fileLocation" placeholder="文件绝对路径" clearable />
    <el-switch
      v-model="isRewirte"
      class="mb-2"
      active-text="覆盖"
      inactive-text="不覆盖"
    />
    <el-button class="dialogButton" type="primary" @click="upFileSubmit">
      提交
    </el-button>
  </el-dialog>

  <div class="custom-tree-container">
    <el-card class="box-card">
      <a style="margin-left: 20px" @click="backDir" v-show="notHome">
        <el-button size="large" type="primary">
          <el-icon :size="20" color="#ffffff"><ArrowLeftBold /></el-icon>
          <a style="font-size: 20px; color: #ffffff">返回</a>
        </el-button>
      </a>
      <a style="margin-left: 20px" @click="openNewdialog">
        <el-button size="large" type="primary">
          <!-- <el-icon :size="20" color="#ffffff"><DocumentAdd /></el-icon> -->
          <a style="font-size: 20px; color: #ffffff">新建文件夹</a>
        </el-button>
      </a>
      <a style="margin-left: 20px" @click="showUpFileDialog">
        <el-button size="large" type="primary">
          <el-icon :size="20" color="#ffffff"><Upload /></el-icon>
          <a style="font-size: 20px; color: #ffffff">上传</a>
        </el-button>
      </a>
      <a style="margin-left: 20px" @click="BackRootHome" v-show="notHome">
        <el-button size="large" type="success">
          <!-- <el-icon :size="20" color="#ffffff"><Home /></el-icon> -->
          <a style="font-size: 20px; color: #ffffff">回家</a>
        </el-button>
      </a>
      <el-tree
        :data="pathList"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        draggable
        @node-drag-start="handleDragStart"
        @node-drag-end="handleDragEnd"
        @node-drop="handleDrop"
        :allow-drop="allowDrop"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <div v-show="!data.dir">
              <el-icon v-show="!data.dir" :size="20" color="#409eff">
                <Files />
              </el-icon>
              <el-icon v-show="data.dir" :size="20" color="#409eff">
                <Folder />
              </el-icon>
              <span style="flex: 1; margin-left: 20px">{{ node.label }}</span>
            </div>
            <div v-show="data.dir" @click="opendir(node, data)">
              <el-icon v-show="!data.dir" :size="20" color="#409eff">
                <Files />
              </el-icon>
              <el-icon v-show="data.dir" :size="20" color="#409eff">
                <Folder />
              </el-icon>
              <span style="flex: 1; margin-left: 20px">{{ node.label }}</span>
            </div>
            <span>
              <el-button-group>
                <a v-show="!data.dir" @click="download(data)">
                  <el-button type="primary">
                    <el-icon :size="20" color="#ffffff"><Download /></el-icon>
                  </el-button>
                </a>
                <a
                  style="margin-left: 10px; margin-right: 10px"
                  @click="openRenamedialog(data)"
                >
                  <el-button type="primary">
                    <el-icon :size="20" color="#ffffff"><Edit /></el-icon>
                  </el-button>
                </a>
                <a style="align-self: flex-end" @click="removeD(node, data)">
                  <el-button type="danger">删除</el-button>
                </a>
              </el-button-group>
              <!-- <a v-show="!data.dir" @click="getTree(data)">查看</a>-->
            </span>
          </span>
        </template>
      </el-tree>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import {
  creatDir,
  getFile,
  remove,
  renameOrMvFile,
  rootPathHDFS,
  UploadFile,
} from '@/api/dfs'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
const notHome = ref(false)
const homeRoot = ref('')
interface jsonObject {
  [key: string]: any
}
const value = ref([])
const select = ref('')
const pathList = ref([])
let dirList = []
let removeJson: jsonObject = {}
const isRewirte = ref(false)
const fileDialog = ref(false)
const curFileName = ref('')
const curFileNameNodo = ref('')
const newDialog = ref(false)
const upFilesDialog = ref(false)
const name = ref('')
const fileLocation = ref('') //文件绝对路径
const curDirLocation = ref('/') //当前所在的目录路径
const dirOptions = [
  {
    value: pathList.value,
    label: '',
    children: [
      {
        value: 'test2',
        label: 'test2',
      },
    ],
  },
]
//点击文件夹后的方法
const opendir = (n, d) => {
  const dir = forDir()
  if (dir)
    initDisk('/' + forDir() + '/' + d.label) //当然先跳转到文件夹的那个路径里
  else initDisk('/' + d.label)
  notHome.value = true //并且将返回按钮展示出来
  dirList.push(d.label)
  curDirLocation.value = forDir()
}
//回家
const BackRootHome = () => {
  notHome.value = false
  initDisk('')
  curDirLocation.value = '/'
}
//初始化的方法
onMounted(() => {
  initDisk('')
  homeRoot.value = '/' + localStorage.getItem('login_user') + '/' //初始化当前用户应该有的根目录
  console.log(homeRoot.value)
})
//初始化目录
const initDisk = async e => {
  const { msg, code, data } = await rootPathHDFS({ r: e })
  pathList.value = data
}

//创建文件夹
const newFileSubmit = async () => {
  const dir = forDir()
  if (dir == '') {
    const { code, msg } = await creatDir({
      path: name.value,
    })
    if (code == 200) {
      ElMessage.success(msg)
      newDialog.value = false
    } else {
      ElMessage.error(msg)
    }
  } else {
    const { code, msg } = await creatDir({
      path: dir + '/' + name.value,
    })
    if (code == 200) {
      ElMessage.success(msg)
      newDialog.value = false
    } else {
      ElMessage.error(msg)
    }
  }
  name.value = ''
  await initDisk('' + forDir())
}
// 上传
const upFileSubmit = async () => {
  //需要拿到当前所在目录
  let dir = forDir()
  dir = dir == '' ? '/' : dir + '/' //如果是根目录需要替换为/
  const wirte = isRewirte.value
  const { code, msg } = await UploadFile(
    [fileLocation.value],
    dir,
    wirte ? 1 : 0
  )
  if (code == 200) {
    ElMessage.success(msg)
    fileLocation.value = ''
    upFilesDialog.value = false
    initDisk('' + forDir())
  } else {
    ElMessage.error(msg)
  }
}
//打开重命名对话框
const openRenamedialog = d => {
  curFileName.value = d.label
  curFileNameNodo.value = d.label
  fileDialog.value = true
}

const openNewdialog = function () {
  newDialog.value = true
}

const showUpFileDialog = function () {
  upFilesDialog.value = true
}
// 返回上一级
const backDir = function () {
  dirList.pop()
  const back = forDir()
  if (back == '') notHome.value = false
  initDisk('' + back)
}

// 路径遍历
function forDir() {
  let dir = ''
  for (let i = 0; i < dirList.length; i++) {
    dir += '/' + dirList[i]
  }
  return dir
}

//下载文件
const download = async p => {
  const name = p.path + p.label
  const data = await getFile({ path: name })
  let blob = new Blob([data])
  const url = window['URL'].createObjectURL(blob)
  console.log('p.path:' + p.path)
  console.log('p.label:' + p.label)
  console.log('name:' + name)
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', `${p.label}`)
  document.body.appendChild(link)
  link.click()
  window['URL'].revokeObjectURL(url)
  window.URL.revokeObjectURL(link.href)
  document.body.removeChild(link)
}

// 删除
const removeD = async (node, data) => {
  const { code, msg } = await remove(data)
  if (code == 200) {
    ElMessage.success(msg)
    newDialog.value = false
  } else {
    ElMessage.error(msg)
  }
  await initDisk('' + forDir())
}
//重命名
const resetFilename = async value => {
  const { code, msg } = await renameOrMvFile({
    src: forDir() + '/' + curFileName.value,
    tar: forDir() + '/' + curFileNameNodo.value,
  })
  if (code == 200) {
    ElMessage.success(msg)
    initDisk('' + forDir())
    fileDialog.value = false
  } else {
    ElMessage.error(msg)
  }
}
//移动文件的时候只需要传入当前的选择路径和被选择文件或者文件夹
//节点被拖拽时触发 共两个参数，依次为：被拖拽节点对应的 Node、event
const handleDragStart = (n, e) => {
  ElNotification({
    title: '温馨提示',
    message: '您正在移动文件',
    type: 'warning',
    duration: 2000,
  })
}
//拖拽结束  共四个参数，依次为：被拖拽节点对应的 Node、结束拖拽时最后进入的节点（可能为空）、被拖拽节点的放置位置（before、after、inner）、event
const handleDragEnd = (n, e) => {}
//完成 	共四个参数，依次为：被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置（before、after、inner）、event
const handleDrop = async (dn, en) => {
  const { code, msg } = await renameOrMvFile({
    src: forDir() + '/' + dn.data.label,
    tar: forDir() + '/' + en.data.label,
  })
  if (code == 200) {
    ElMessage.success(msg)
  } else {
    ElMessage.error(msg)
  }
  initDisk('' + forDir())
}

//拖拽时判定目标节点能否成为拖动目标位置。只要是文件夹就可以拖进去 其它的不行
const allowDrop = (dn, d, t) => {
  return d.data.dir
}
</script>

<style>
.box-card {
  width: 100%;
  height: 80%;
}

.custom-tree-node {
  display: flex;
  width: 84vw;
  align-items: center;
  justify-items: flex-end;
  justify-content: space-between;
  font-size: 20px;
}
.dialogButton {
  width: 200px;
  height: 36px;
  font-size: 20px;
}
.el-dialog__body {
  display: flex;
  flex-direction: column;
}
.el-radio-group {
  margin-bottom: 10px;
}
.el-input__wrapper {
  margin-bottom: 10px;
}
.el-tree-node__content {
  height: 40px;
}
.el-tree {
  margin-top: 20px;
}
</style>
